package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private static final ExecutorService executor = Executors.newFixedThreadPool(10);

    @Override
    public Result queryById(Long id) {

//        Shop shop1 = queryWithPassThrough(id);
        String key = CACHE_SHOP_KEY + id;

//        Shop shop = queryWithMutex(id);
        Shop shop = queryWithLogicTime(id);
        if (shop == null) {
            return Result.fail("店铺不存在！");
        }
        //6.返回
        return Result.ok(shop);
    }

    public Shop queryWithLogicTime(Long id) {

        String key = CACHE_SHOP_KEY + id;//缓存key
        String lockKey = LOCK_SHOP_KEY + id;//互斥锁key
        //1.redis里取商铺信息
        String redisDataJson = stringRedisTemplate.opsForValue().get(key);

        //2.判断是否命中
        //3.未命中直接返回null
        if (redisDataJson == null || StrUtil.equals(redisDataJson, "")) {
            return null;
        }


            //4.命中，判断缓存是否过期
            RedisData redisData = JSONUtil.toBean(redisDataJson, RedisData.class);
            JSONObject data = (JSONObject) redisData.getData();
            Shop shop = JSONUtil.toBean(data, Shop.class);
            LocalDateTime expireTime = redisData.getExpireTime();


            //4.2过期，尝试获取互斥锁
            if (LocalDateTime.now().isAfter(expireTime)) {
                System.out.println(expireTime);
                boolean isLock = tryLock(lockKey);
                //5.判断是否获取互斥锁
                if (isLock) {
                    //5.2获取互斥锁，开启独立线程
                    executor.submit(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                //6.1将商铺信息写入redis并设置逻辑过期时间
                                setRedisData(id, LocalDateTime.now().plusSeconds(20));
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            } finally {
                                unlock(lockKey);
                            }
                        }
                    });
                }

            }
            //4.1未过期，返回商铺信息
            //5.1未获取互斥锁，返回商铺信息
            return shop;

    }

    /**
     * 互斥锁解决击穿问题
     *
     * @param id
     * @return
     */
    public Shop queryWithMutex(Long id) {
        String key = CACHE_SHOP_KEY + id;//缓存key
        String lockKey = LOCK_SHOP_KEY + id;//互斥锁key
        //1.redis里取商铺信息
        String shopJson = stringRedisTemplate.opsForValue().get(key);

        //2.存在返回商铺信息

        if (StrUtil.isNotBlank(shopJson)) {
            log.info("获得redis值");
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        //2.1redis返回是""
        if (shopJson != null) {
            return null;
        }
        Shop shop = null;

        try {
            //3.未命中尝试获取互斥锁

            boolean isLock = tryLock(lockKey);
            //3.1判断是否获取互斥锁
            if (!isLock) {
                //3.2未获取互斥锁休眠一段时间并再度调用自身
                Thread.sleep(50);
                return queryWithMutex(id);

            }
            //3.3获取互斥锁，查询数据库

            shop = getById(id);
            log.info("完成数据库查询！");
            //模拟延迟
            Thread.sleep(200);
            //4.mysql不存在，空值写入redis
            if (null == shop) {

                stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            //5.mysql存在，写入redis
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
            log.info("释放锁成功！");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            //6.释放互斥锁
            log.info("释放锁成功！");
            unlock(lockKey);

        }
        //7.返回
        return shop;
    }

    /**
     * 缓存穿透解决方案代码
     *
     * @param id
     * @return
     */
    public Shop queryWithPassThrough(Long id) {
        String key = CACHE_SHOP_KEY + id;

        //1.redis里取商铺信息
        String shopJson = stringRedisTemplate.opsForValue().get(key);

        //2.存在返回商铺信息

        if (StrUtil.isNotBlank(shopJson)) {
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }
        //2.1redis返回是""
        if (shopJson != null) {
            return null;
        }

        //3.不存在查询mysql
        Shop shop = getById(id);

        //4.mysql不存在，空值写入redis
        if (null == shop) {

            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }

        //5.mysql存在，写入redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);

        //6.返回
        return shop;

    }

    /**
     * 获取互斥锁
     *
     * @param key
     * @return
     */
    private boolean tryLock(String key) {
        //设置redis的锁
        Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        if (BooleanUtil.isTrue(aBoolean)) {
            log.info("获取锁成功！" + aBoolean);
        }
        if (!BooleanUtil.isTrue(aBoolean)) {
            log.info("获取锁失败！" + aBoolean);
        }
        return BooleanUtil.isTrue(aBoolean);
    }

    /**
     * 释放锁
     *
     * @param key
     */
    private void unlock(String key) {

        stringRedisTemplate.delete(key);
    }


    public void setRedisData(Long id, LocalDateTime time) throws InterruptedException {
        //0.查询shop
        Shop shop = getById(id);
        Thread.sleep(200);
        //1.初始化redisData
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(time);
        //2.将redisData转换成String
        String redisDataJson = JSONUtil.toJsonStr(redisData);
        //3.写入redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, redisDataJson);
        System.out.println("时间：" + time);
    }

    public Shop getByIdTest(Long id) {
        return getById(id);
    }

    @Override
    @Transactional
    public Result updateShop(Shop shop) {
        //1.确认id是否为空，空报错
        Long id = shop.getId();
        if (id == null) {

            return Result.fail("店铺id不能为空！");
        }

        //2.修改数据库
        updateById(shop);

        //3.删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + id);
        return Result.ok();
    }
}
